# -*- coding: utf-8 -*-

from flask import current_app as app
from app.db.models.asset_tasks import AssetTasks

WEB_SECURITY_LIST = ["vul", "securityEvent", "ssl", "content"]


class UpdateUnenableTask:

    def __init__(self):
        self.enable_monitor = {}
        self.unenable_monitor = {}
        self.init()

    def init(self):
        for _ in AssetTasks.objects.filter(triggerType="schedule", taskGroupType="web_security"):
            enable_list = []
            for key in WEB_SECURITY_LIST:
                settings = getattr(_, f"{key}Settings")
                enable_list.append(settings.enable)
            if enable_list and not any(enable_list):
                if _.enableMonitor:
                    self.enable_monitor.setdefault(_.uid, []).append(_.id)
                else:
                    self.unenable_monitor.setdefault(_.uid, []).append(_.id)
        app.logger.info(f"未开启监测开关用户数: {len(self.unenable_monitor.keys())}, 任务数: {sum([len(_) for _ in self.unenable_monitor.values()])}")
        app.logger.info(f"开启监测开关用户数: {len(self.enable_monitor.keys())}, 任务数: {sum([len(_) for _ in self.enable_monitor.values()])}")
        with open("unenable_monitor.csv", "w") as f:
            f.write("\n".join([str(_) for v in self.unenable_monitor.values() for _ in v]))

    def run(self):
        for _ in AssetTasks.objects.filter(pk__in=[_ for v in self.unenable_monitor.values() for _ in v]):
            for key in WEB_SECURITY_LIST:
                settings = getattr(_, f"{key}Settings")
                if settings.taskId:
                    settings.enable = True
            app.logger.info(_.id)
            _.save()
